package com.itxuhang.mvc.mapping;

import com.itxuhang.spring.aware.BeanFactoryAware;
import com.itxuhang.spring.factory.BeanFactory;
import com.itxuhang.spring.factory.DefaultListableBeanFactory;
import com.itxuhang.spring.init.InitializingBean;
import com.itxuhang.spring.po.BeanDefinition;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanNameUrlHandlerMapping implements HandlerMapping, BeanFactoryAware, InitializingBean {

    private Map<String,Object> urlHandlers = new HashMap<>();
    private DefaultListableBeanFactory beanFactory;
    public BeanNameUrlHandlerMapping(){
        // 建立uri和handler的映射

//        urlHandlers.put("/queryUser",new QueryUserHandler());
//        urlHandlers.put("/saveUser",new SaveUserHandler());

    }

    //根据请求URI查找对应的handler
    @Override
    public Object getHandler(HttpServletRequest request){
        String uri = request.getRequestURI();
        if(uri == null || uri.equals("")){
            return null ;
        }
        return this.urlHandlers.get(uri);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }

    @Override
    public void afterPropertiesSet() {
        List<BeanDefinition> beanDefinitions = beanFactory.getBeanDefinitions();
        for (BeanDefinition bd : beanDefinitions) {
            String beanName = bd.getBeanName();
            if (beanName.startsWith("/")){
                urlHandlers.put(beanName,beanFactory.getBean(beanName));
            }
        }
    }
}
